package run.iget.framework.common.util;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class DateUtils extends DateUtil {

    /**
     * 日期解析格式
     */
    private static final String[] DATE_PARSE_PATTERNS = new String[]{
            DatePattern.NORM_DATETIME_PATTERN,
            DatePattern.NORM_DATE_PATTERN,
            DatePattern.NORM_DATETIME_MINUTE_PATTERN,
            DatePattern.UTC_MS_PATTERN,
            DatePattern.UTC_MS_WITH_XXX_OFFSET_PATTERN,
            DatePattern.UTC_MS_WITH_ZONE_OFFSET_PATTERN,
            DatePattern.UTC_PATTERN,
            DatePattern.UTC_WITH_XXX_OFFSET_PATTERN,
            DatePattern.NORM_MONTH_PATTERN,
            "yyyy.MM.dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy.MM.dd HH:mm",
            "yyyy/MM/dd", "yyyy.MM.dd", "yyyy/MM", "yyyy.MM"};

    /**
     * 将字符串，尝试转为日期格式
     * 支持的日期格式如下 DateUtils#DATE_PARSE_PATTERNS
     *
     * @param text
     * @return
     * @see DateUtils#DATE_PARSE_PATTERNS
     */
    public static Date tryParse(String text) {
        if (StrUtil.isNumeric(text)) {
            return new Date(Long.parseLong(text));
        }
        Calendar calendar = DateUtil.parseByPatterns(text, DATE_PARSE_PATTERNS);
        Date date = calendar.getTime();
        // 前端传的的时间格式：yyyy-MM-dd'T'HH:mm:ssZ，转换会丢掉时区，顾需要添加上
        if (text.endsWith("Z")) {
            return DateUtil.offsetMillisecond(date, TimeZone.getDefault().getRawOffset());
        }
        return date;
    }

    /**
     * 将字符串转为 LocalDateTime
     *
     * @param text
     * @return
     * @see DateUtils#tryParse(String)
     */
    public static LocalDateTime tryParseLocalDateTime(String text) {
        Date date = tryParse(text);
        return DateUtil.toLocalDateTime(date);
    }

    /**
     * 将字符串转为 LocalDate
     *
     * @param text
     * @return
     * @see DateUtils#tryParseLocalDateTime(String)
     */
    public static LocalDate tryParseLocalDate(String text) {
        LocalDateTime localDateTime = tryParseLocalDateTime(text);
        return localDateTime.toLocalDate();
    }


}
